package per.wsj.httplib.ok.ext

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import per.wsj.httplib.ok.LoadState
import per.wsj.httplib.ok.exception.ExceptionUtils

/**
 * ViewModel extensions：start coroutine
 * @param loadState
 * @param block
 */
fun ViewModel.launch(
    loadState: (state: LoadState) -> Unit,
    block: suspend CoroutineScope.() -> Unit
) {
    viewModelScope.launch(
        CoroutineExceptionHandler { _, throwable ->
            run {
                // handle error
                val error = ExceptionUtils.parseException(throwable)
                loadState(LoadState.Error(error))
            }
        }
    ) {
        try {
            loadState(LoadState.Start)
            block.invoke(this)
        } finally {
            loadState(LoadState.Finish)
        }
    }
}